import BundleManager from "../core/BundleManager";
import EventManager from "../core/EventManager";
import ResManager from "../core/ResManager";
import SceneNavigator from "../core/SceneNavigator";
import BundleUpdateModule from "../module/BundleUpdateModule";
import { HttpRequest } from "../net/HttpRequest";
import LogUtil from "../utils/LogUtil";
import MathUtil from "../utils/MathUtil";
import { UIManager } from "../core/UIManager";
import { NetInfo } from "../net/Commond";
import PopupManager from "../core/PopupManager";
import GuideData from "../data/GuideData";
import { CommonEvents } from "../net/CommonEvents";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameItem extends cc.Component {

    @property({ type: cc.Sprite, tooltip: CC_DEV && '背景图' })
    public background: cc.Sprite = null;

    @property({ type: cc.Label, tooltip: CC_DEV && '游戏名' })
    public gameName: cc.Label = null;

    @property({ type: cc.Node, tooltip: CC_DEV && '更新节点' })
    public updateNode: cc.Node = null;

    @property({ type: cc.Sprite, tooltip: CC_DEV && '进度图' })
    public progressSp: cc.Sprite = null;

    @property({ type: cc.Label, tooltip: CC_DEV && '进度文本' })
    public progressLb: cc.Label = null;

    @property({ type: cc.Sprite, tooltip: CC_DEV && '下载图' })
    public downSp: cc.Sprite = null;

    @property({ type: cc.Sprite, tooltip: CC_DEV && '更新图' })
    public updateSp: cc.Sprite = null;

    data: any = null;

    onLoad() {
        EventManager.on(CommonEvents.BUNDLEUPDATE_FINISH, this.onBundleUpdateFinish, this);
        EventManager.on(CommonEvents.BUNDLEUPDATE_RATE, this.onBundletUpdateRate, this);
        this.updateNode.active = false;
    }

    onDestroy() {
        EventManager.off(CommonEvents.BUNDLEUPDATE_FINISH, this.onBundleUpdateFinish, this);
        EventManager.off(CommonEvents.BUNDLEUPDATE_RATE, this.onBundletUpdateRate, this);
    }

    onBundleUpdateFinish(params: any[]) {
        if (!this.data || !this.data.remoteVersionUrl) return;
        if (this.data.name != params[0]) return;
        let bundleName = params[0];
        let result = params[1];
        let text = `${bundleName}热更完成，热更result：${result}`;
        LogUtil.log(text);
        this.downSp.node.active = false;
        this.updateNode.active = false;
        if (result) {
            this.scheduleOnce(() => {
                UIManager.ins().hideUILoading();
                this.loadBundle();
            }, 0.5);
        }
    }

    onBundletUpdateRate(params: any[]) {
        if (!this.data || !this.data.remoteVersionUrl) return;
        if (this.data.name != params[0]) return;
        let bundleName = params[0];
        let rate = params[1];
        let text = `${bundleName}热更进度：${rate}`;
        LogUtil.log(text);

        let _progress = MathUtil.getProgress(rate);
        this.downSp.node.active = false;
        this.updateNode.active = true;
        this.progressLb.string = _progress + "%";
        this.progressSp.fillRange = rate;
    }

    init(data: any): void {
        this.node.active = data ? true : false;
        if(data){
            this.node.name = data.name;
            this.data = data;
            let config_language = ResManager.ins().getRes('config_language');
            this.gameName.string = config_language[data.name] ? config_language[data.name].text : data.name;
        }
    }

    onClick(): void {
        if(this.updateNode.active){
            UIManager.ins().showMessage("下载中...");
            return;
        }
        if (this.data.remoteVersionUrl) {
            if (!cc.sys.isNative) {
                this.loadBundle();
                return;
            }
            //这里检查一下是否已经加载过bundle，如果加载过就先释放，否则会造成更新之后用老的资源
            BundleManager.ins().releaseAll(this.data.name);
            LogUtil.log('开始热跟新>>');
            this.checkRemoteVersion();
        } else {
            if(this.data.type == 1){
                //聊天引导结束
                if(this.data.name == 'chat'){
                    GuideData.ins().complete(100);
                }
                SceneNavigator.go(this.data.scene, {});
            }else{
                this.loadBundle();
            }
        }
    }

    loadBundle() {
        BundleManager.ins().loadBundle(this.data.name, `scene/${this.data.scene}`, (scene) => {
            cc.director.runScene(scene);
        });
    }

    checkRemoteVersion() {
        BundleUpdateModule.ins().loadManifest(this.data.name, (version: string) => {
            UIManager.ins().showUILoading(0);
            BundleUpdateModule.ins().setBundleVersion(this.data.name, version);
            let remoteVersionUrl = this.data.remoteVersionUrl.format(NetInfo.ip);
            LogUtil.log('remoteVersionUrl>>',remoteVersionUrl);
            let httpPromise = HttpRequest.ins().httpPromise(remoteVersionUrl, {}, 'get', () => {
                UIManager.ins().hideUILoading();
                //网络请求失败直接进入游戏
                PopupManager.show('prefabs/PopBox', {
                    title: '提示',
                    content: '请求远程版本失败，是否进入当前版本',
                    confirmCallback:()=>{
                        this.loadBundle();
                    }
                });
            });
            httpPromise.then((data: any) => {
                LogUtil.log(`serverVersion:${data.version},localVersion:${version}`);
                if (MathUtil.versionCompare(data.version, version)) {
                    this.updateNode.active = true;
                    BundleUpdateModule.ins().setBundleVersion(this.data.name, data.version);
                    BundleUpdateModule.ins().hotUpdate();
                } else {
                    UIManager.ins().hideUILoading();
                    this.loadBundle();
                }
            }).catch(() => {
                UIManager.ins().hideUILoading();
            });
        });
    }
}